package com.micro.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * @author dufen
 */
@Slf4j
public class AesUtil {
    /**
     * AES-128 CBC 解密
     *
     * @param bytes
     * @param key
     * @param iv
     * @return
     */
    public static byte[] decrypt(byte[] bytes, byte[] key, String iv) {
        try {
            if (key == null || key.length != 16) {
                throw new RuntimeException("加密key不能为空或其长度只能等于16");
            }
            SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
            byte[] ivBytes = "0000000000000000".getBytes(StandardCharsets.UTF_8);
            if (StringUtils.isNotBlank(iv)) {
                ivBytes = iv.substring(0, 16).getBytes(StandardCharsets.UTF_8);
            }
            IvParameterSpec spec = new IvParameterSpec(ivBytes);
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, spec);
            return cipher.doFinal(bytes);
        } catch (NoSuchAlgorithmException e) {
            log.info("没有这样的算法异常{}", e);
        } catch (NoSuchPaddingException e) {
            log.info("没有这样的填充{}", e);
        } catch (InvalidAlgorithmParameterException e) {
            log.info("无效的算法参数异常{}", e);
        } catch (InvalidKeyException e) {
            log.info("无效密钥异常{}", e);
        } catch (IllegalBlockSizeException e) {
            log.info("非法块大小异常{}", e);
        } catch (BadPaddingException e) {
            log.info("错误填充异常{}", e);
        }
        return new byte[0];
    }
}
